<template>
  <div class="wrapper">
    <div class="operation">
      <Button @click="addParent" icon="md-add">添加一级分类</Button>
      选择分类:
      <Select @on-change="changeSortCate" v-model="sortCate" style="width:200px">
        <Option v-for="item in sortCateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>

    </div>
    <tree-table ref="treeTable" size="default" :loading="loading" :data="tableData" :columns="columns" :border="true" :show-index="false" :is-fold="true" :expand-type="false" primary-key="id">

      <template slot="action" slot-scope="scope">
        <Dropdown v-show="scope.row.level == 2"  transfer="true" trigger="click">
          <Button size="small">
            绑定
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem @click.native="brandOperation(scope.row)">编辑绑定品牌</DropdownItem>
            <DropdownItem @click.native="specOperation(scope.row)">编辑绑定规格</DropdownItem>
            <DropdownItem @click.native="parameterOperation(scope.row)">编辑绑定参数</DropdownItem>
          </DropdownMenu>
        </Dropdown>

        &nbsp;
        <Dropdown transfer="true" trigger="click">
          <Button size="small">
            操作
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem @click.native="edit(scope.row)">编辑</DropdownItem>
            <DropdownItem v-if="scope.row.deleteFlag == 1" @click.native="enable(scope.row)">启用</DropdownItem>
            <DropdownItem v-if="scope.row.deleteFlag == 0" @click.native="disable(scope.row)">禁用</DropdownItem>
            <DropdownItem @click.native="remove(scope.row)">删除</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        &nbsp;
        <Button v-show="scope.row.level != 2" type="primary" @click="addChildren(scope.row)" size="small" icon="md-add" style="margin-right: 5px">添加子分类
        </Button>
      </template>

      <template slot="commissionRate" slot-scope="scope">
        {{ scope.row.commissionRate }}%
      </template>

      <template slot="deleteFlag" slot-scope="scope">
        <div v-if="scope.row.deleteFlag == 0">
          <Badge text="正常启用" status="success"></Badge>
        </div>
        <div v-if="scope.row.deleteFlag == 1">
          <Badge text="禁用" status="error"></Badge>
        </div>
      </template>
    </tree-table>

    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable="false" :width="500">
      <Form ref="form" :model="formAdd" :label-width="100" :rules="formValidate">
        <div v-if="showParent">
          <FormItem label="上级分类" prop="parentId">
            {{ parentTitle }}
            <Input v-model="formAdd.parentId" clearable style="width: 100%; display: none" />
          </FormItem>
        </div>
        <FormItem label="层级" prop="level" style="display: none">
          <Input v-model="formAdd.level" clearable style="width: 100%" />
        </FormItem>
        <FormItem label="分类名称" prop="name">
          <Input v-model="formAdd.name" clearable style="width: 100%" />
        </FormItem>
        <FormItem label="分类图标" prop="image">
          <upload-pic-input v-model="formAdd.image" style="width: 100%"></upload-pic-input>
        </FormItem>
        <FormItem label="排序值" prop="sortOrder" style="width: 345px">
          <InputNumber v-model="formAdd.sortOrder"></InputNumber>
        </FormItem>
        <FormItem label="佣金比例(%)" prop="commissionRate" style="width: 345px">
          <InputNumber v-model="formAdd.commissionRate"></InputNumber>
        </FormItem>
        <FormItem label="是否启用" prop="deleteFlag">
          <i-switch size="large" v-model="formAdd.deleteFlag" :true-value="0" :false-value="1">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modalVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="Submit">提交</Button>
      </div>
    </Modal>

    <Modal :title="modalBrandTitle" v-model="modalBrandVisible" :mask-closable="false" :width="500">
      <Form ref="brandForm" :model="brandForm" :label-width="100">
        <Select v-model="brandForm.categoryBrands" multiple>
          <Option v-for="item in brandWay" :value="item.id" :key="item.id">{{ item.name }}</Option>

        </Select>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modalBrandVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="saveCategoryBrand">提交</Button>
      </div>
    </Modal>

    <Modal :title="modalSpecTitle" v-model="modalSpecVisible" :mask-closable="false" :width="500">
      <Form ref="specForm" :model="specForm" :label-width="100">
        <Select v-model="specForm.category_specs" multiple>
          <Option v-for="item in specifications" :value="item.id" :key="item.id" :label="item.specName">
          </Option>
        </Select>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modalSpecVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="saveCategorySpec">提交</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  insertCategory,
  updateCategory,
  getBrandListData,
  delCategory,
  getCategoryBrandListData,
  saveCategoryBrand,
  getSpecificationList,
  getCategorySpecListData,
  disableCategory,
  saveCategorySpec,
  getCategoryTree,
} from "@/api/goods";
import TreeTable from "@/views/my-components/tree-table/Table/Table";
import uploadPicInput from "@/views/my-components/lili/upload-pic-input";
import * as filters from "@/utils/filters";

export default {
  name: "lili-components",
  components: {
    TreeTable,
    uploadPicInput,
  },
  data() {
    return {
      categoryList: [], // 分类列表
      sortCateList: [], //筛选出分类第一级
      sortCate: "", //筛选的数据
      loading: false, // 加载状态
      selectCount: 0, // 选择数量
      brands: [], //品牌集合
      specifications: [], //规格集合
      categoryId: "", // 分类id
      category_brands: [], //已经选择的品牌
      category_specs: [], //已经选择的规格
      expandLevel: 1, // 展开层级
      modalType: 0, // 添加或编辑标识
      modalVisible: false, // 添加或编辑显示
      modalBrandVisible: false, //品牌关联编辑显示
      modalSpecVisible: false, //品牌关联编辑显示
      modalTitle: "", // 添加或编辑标题
      showParent: false, // 是否展示上级菜单
      parentTitle: "", // 父级菜单名称
      modalBrandTitle: "",
      modalSpecTitle: "",
      formAdd: {
        // 添加或编辑表单对象初始化数据
        parentId: "",
        name: "",
        image: "",
        sortOrder: "",
        deleteFlag: 0,
        commissionRate: "",
        level: 0,
      },
      brandForm: {
        categoryBrands: [],
      },
      brandWay: "", //请求绑定品牌的信息
      specForm: {},
      // 表单验证规则
      formValidate: {},
      columns: [
        {
          title: "分类名称",
          key: "name",
          minWidth: "120px",
        },
        {
          title: "状态",
          key: "deleteFlag",
          headerAlign: "center",
          type: "template",
          template: "deleteFlag",
        },
        {
          title: "佣金(%)",
          key: "commissionRate",
          headerAlign: "center",
          type: "template",
          template: "commissionRate",
        },
        {
          fixed: "right",
          title: "操作",
          key: "action",
          align: "left",
          headerAlign: "center",
          type: "template",
          template: "action",
        },
      ],
      tableData: [],
    };
  },
  methods: {

    changeSortCate(val) {
      let way = this.categoryList.find((item) => {
        return item.name == val;
      });
      this.tableData = [way];
    },
    init() {
      this.getAllList(0);
      this.getBrandList();
      this.getSpecList();
    },
    //获取所有品牌
    getBrandList() {
      getBrandListData().then((res) => {
        this.brandWay = res;
      });
    },
    //获取所有规格
    getSpecList() {
      getSpecificationList().then((res) => {
        if (res.success) {
          this.specifications = res;
        }
      });
    },
    //弹出品牌关联框
    brandOperation(v) {
      getCategoryBrandListData(v.id).then((res) => {
        console.warn(res)
        this.categoryId = v.id;
        this.modalBrandTitle = "品牌关联";
        this.brandForm.categoryBrands = res.result.map((item) => item.id);
        // this.brandWay = {...res.result}
        this.modalBrandVisible = true;
      });
    },
    //弹出规格关联框
    specOperation(v) {
      getCategorySpecListData(v.id).then((res) => {
        this.categoryId = v.id;
        this.modalSpecTitle = "规格关联";
        this.specForm.category_specs = res.map((item) => item.id);
        this.modalSpecVisible = true;
      });
    },
    //保存分类规格绑定
    saveCategorySpec() {
      saveCategorySpec(this.categoryId, this.specForm).then((res) => {
        this.submitLoading = false;
        if (res.success) {
          this.$Message.success("操作成功");
          this.modalSpecVisible = false;
        }
      });
    },
    //保存分类品牌绑定
    saveCategoryBrand() {
      saveCategoryBrand(this.categoryId, this.brandForm).then((res) => {
        this.submitLoading = false;
        if (res.success) {
          this.$Message.success("操作成功");
          this.modalBrandVisible = false;
        }
      });
    },
    parameterOperation(v) {
      this.$router.push({ name: "parameter", query: { id: v.id } });
    },
    refresh() {
      this.loading = true;
      let that = this;
      setTimeout(function () {
        that.loading = false;
      }, 1000);
    },
    addChildren(v) {
      this.modalType = 0;
      this.modalTitle = "添加子分类";
      this.parentTitle = v.name;
      this.formAdd.level = eval(v.level + "+1");
      this.showParent = true;
      // this.$refs.form.resetFields();
      delete this.formAdd.id;
      this.formAdd.parentId = v.id;
      this.modalVisible = true;
    },
    edit(v) {
      this.modalType = 1;
      this.modalTitle = "编辑";
      this.formAdd.id = v.id;
      this.formAdd.name = v.name;
      this.formAdd.level = v.level;
      this.formAdd.parentId = v.parentId;
      this.formAdd.sortOrder = v.sortOrder;
      this.formAdd.commissionRate = v.commissionRate;
      this.formAdd.deleteFlag = v.deleteFlag;
      this.formAdd.image = v.image;
      this.showParent = false;
      this.modalVisible = true;
    },
    addParent() {
      this.modalType = 0;
      this.modalTitle = "添加一级分类";
      this.parentTitle = "顶级分类";
      this.showParent = true;
      this.$refs.form.resetFields();
      delete this.formAdd.id;
      this.formAdd.parentId = 0;
      this.modalVisible = true;
    },
    Submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.modalType === 0) {
            // 添加 避免编辑后传入id等数据 记得删除
            delete this.formAdd.id;
            insertCategory(this.formAdd).then((res) => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("添加成功");
                this.getAllList(0);
                this.modalVisible = false;
                this.$refs.form.resetFields();
              }
            });
          } else {
            // 编辑
            updateCategory(this.formAdd).then((res) => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("修改成功");
                this.getAllList(0);
                this.modalVisible = false;
                this.$refs.form.resetFields();
              }
            });
          }
        }
      });
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        // 记得确认修改此处
        content: "您确认要删除 " + v.name + " ?",
        loading: true,
        onOk: () => {
          // 删除
          delCategory(v.id).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getAllList(0);
            }
          });
        },
      });
    },
    getAllList(parent_id) {
      this.loading = true;
      getCategoryTree(parent_id).then((res) => {
        this.loading = false;
        if (res.success) {
          // 仅展开指定级数 默认后台已展开所有
          let expandLevel = this.expandLevel;
          localStorage.setItem("category", JSON.stringify(res.result));
          res.result.forEach((e, index, arr) => {
            this.sortCateList.push({
              label: e.name,
              value: e.name,
            });
            this.sortCate = arr[0].name;
            if (expandLevel == 1) {
              if (e.level == 0) {
                e.expand = false;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function (c) {
                  if (c.level == 1) {
                    c.expand = false;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function (b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            } else if (expandLevel == 2) {
              if (e.level == 0) {
                e.expand = true;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function (c) {
                  if (c.level == 1) {
                    c.expand = false;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function (b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            } else if (expandLevel == 3) {
              if (e.level == 0) {
                e.expand = true;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function (c) {
                  if (c.level == 1) {
                    c.expand = true;
                  }
                  if (c.children && c.children.length > 0) {
                    c.children.forEach(function (b) {
                      if (b.level == 2) {
                        b.expand = false;
                      }
                    });
                  }
                });
              }
            }
          });

          this.categoryList = res.result;
          this.tableData = [res.result[0]];
        }
      });
    },
    enable(v) {
      this.$Modal.confirm({
        title: "确认启用",
        content: "您是否要启用当前分类 " + v.name + " 及其子分类?",
        loading: true,
        okText: "是",
        cancelText: "否",
        onOk: () => {
          disableCategory(v.id, { enableOperations: 0 }).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getAllList(0);
            }
          });
        },
        onCancel: () => {
          this.getAllList(0);
        },
      });
    },
    disable(v) {
      this.$Modal.confirm({
        title: "确认禁用",
        content: "您是否要禁用当前分类 " + v.name + " 及其子分类?",
        loading: true,
        okText: "是",
        cancelText: "否",
        onOk: () => {
          disableCategory(v.id, { enableOperations: true }).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getAllList(0);
            }
          });
        },
        onCancel: () => {
          this.getAllList(0);
        },
      });
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/table-common.scss";
.wrapper {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 20px;
}
.article {
  font-size: 16px;
  font-weight: 400;
  margin: 12px 0;
}

.href-text {
  font-size: 12px;
}

.operation {
  margin-bottom: 2vh;
}

.select-count {
  font-weight: 600;
  color: #40a9ff;
}
</style>
